<template>
    <div class="baranch">
        <el-row size="mini" style="height: 100%">
            <el-col :span="12" class="col-wrap" style="height: 100%">
                <el-row class="border-box">
                    <!-- 计算公式展示框 -->
                    <el-col :span="12" class="search-wrap">
                        <el-tooltip
                            class="item"
                            effect="dark"
                            :content="calculateShowLogic ? calculateShowLogic : ''"
                            placement="top-start"
                            :disabled="calculateShowLogic == ''"
                        >
                            <el-input v-model="calculateShowLogic" :title="calculateShowLogic" size="mini" disabled></el-input>
                        </el-tooltip>
                    </el-col>
                    <!-- 模板选择框 -->
                    <el-col :span="7" class="search-wrap">
                        <!-- <el-select
                            v-model="entryBranch.templateCode"
                            :disabled="showData"
                            placeholder="请选择分支模板"
                            size="mini"
                            style="width: 100%"
                            clearable
                            filterable
                        >
                            <el-option
                                v-for="i in templateStorageQuery"
                                :key="i.templateCode"
                                :label="i.templateCode + ' ' + i.templateName"
                                :value="i.templateCode"
                                :disabled="['2', '3'].includes(i.modifyType)"
                            >
                            </el-option>
                        </el-select> -->
                        <Treeselect
                            class="treeselectLeft"
                            ref="treeselect1"
                            v-model="entryBranch.templateCode"
                            :options="templateStorageTree"
                            disableBranchNodes
                            placeholder="请选择分支模板"
                            noOptionsText="暂无数据"
                            noResultsText="无匹配数据"
                            noChildrenText="暂无数据"
                            :popper-append-to-body="false"
                        ></Treeselect>
                    </el-col>
                    <!-- 添加模板按钮 -->
                    <el-col :span="3" class="search-wrap">
                        <el-button @click="handleAddTemplate" :disabled="showData" style="float: right" size="mini" type="primary">添加</el-button>
                    </el-col>
                    <!-- 刷新按钮 -->
                    <el-col :span="2" class="search-wrap">
                        <el-button
                            @click="handleRefresh"
                            :disabled="showData"
                            :loading="refreshBtnLoading"
                            size="mini"
                            icon="el-icon-refresh-right"
                            title="刷新"
                        ></el-button>
                    </el-col>
                </el-row>
                <el-row class="border-box">
                    <!-- 分支拼接符 -->
                    <el-col :span="4" class="search-wrap">
                        <el-select
                            v-model="entryBranch.countType"
                            :disabled="showData"
                            placeholder="请选择"
                            size="mini"
                            style="width: 100%"
                            clearable
                        >
                            <el-option
                                v-for="itme in countTypeStorage"
                                :key="itme.dictKey"
                                :label="itme.dictKey + ' ' + itme.dictKeyName"
                                :value="itme.dictKey"
                            ></el-option>
                        </el-select>
                    </el-col>
                    <!-- 计算因子选择框 -->
                    <el-col :span="12" class="search-wrap">
                        <!-- <el-select
                            v-model="entryBranch.factorCode"
                            @change="changBranchName($event)"
                            :disabled="showData"
                            placeholder="请选择"
                            size="mini"
                            style="width: 100%"
                            clearable
                            filterable
                        >
                            <el-option
                                v-for="c in factorStorageQuery"
                                :key="c.entryCalculateFactorCode"
                                :title="c.entryCalculateFactorCode + ' ' + c.entryCalculateFactorName"
                                :label="c.entryCalculateFactorCode + ' ' + c.entryCalculateFactorName"
                                :value="c.entryCalculateFactorCode"
                            ></el-option>
                        </el-select> -->
                        <Treeselect
                            ref="treeselect2"
                            v-model="entryBranch.factorCode"
                            :options="factorStorageTree"
                            :default-expand-level="1"
                            :value-consists-of="'LEAF_PRIORITY'"
                            @select="changBranchName"
                            @input="changBranchName2"
                            disableBranchNodes
                            placeholder="请选择计算因子"
                            noOptionsText="暂无数据"
                            noResultsText="无匹配数据"
                            noChildrenText="暂无数据"
                            :popper-append-to-body="false"
                        >
                        </Treeselect>
                    </el-col>
                    <!-- 分支名称框 -->
                    <el-col :span="6" class="search-wrap">
                        <el-input
                            v-model="entryBranch.branchName"
                            :title="entryBranch.branchName"
                            :disabled="showData"
                            placeholder="请输入分支名称"
                            size="mini"
                        ></el-input>
                    </el-col>
                    <!-- 添加 -->
                    <el-col :span="2" class="search-wrap">
                        <el-button
                            @click="handleAddTree"
                            :disabled="showData"
                            icon="el-icon-circle-plus-outline"
                            size="mini"
                            type="primary"
                            title="添加"
                        ></el-button>
                    </el-col>
                </el-row>
                <el-row class="border-box" style="height: calc(100% - 80px)">
                    <!-- 分支树 -->
                    <el-col :span="22" class="search-wrap" style="height: 100%">
                        <div class="tree-box">
                            <el-tree
                                size="mini"
                                ref="tree"
                                id="tree"
                                default-expand-all
                                :data="riskEntryBranchTree"
                                :props="treeProps"
                                @node-click="handleTreeClick"
                                node-key="branchNo"
                                :expand-on-click-node="false"
                            >
                                <span class="custom-tree-node" slot-scope="{ node, data }">
                                    <span>{{ node.label }}</span>
                                    <i
                                        class="el-icon-setting"
                                        style="font-size: 20px; margin-left: 3px; vertical-align: bottom"
                                        :style="{ display: data.existDynamicCfg ? '' : 'none', color: data.existDynamicCfgColor }"
                                        @click="handleCalcExtend(data)"
                                    />
                                </span>
                            </el-tree>
                        </div>
                    </el-col>
                    <el-col :span="2" class="search-wrap">
                        <!-- 修改 -->
                        <el-button
                            @click="handleUpdateTree"
                            :disabled="showData"
                            size="mini"
                            icon="el-icon-check"
                            type="primary"
                            title="保存"
                        ></el-button>
                        <!-- 删除 -->
                        <div style="margin-top: 10px">
                            <el-button
                                @click="handleDeleteTree"
                                :disabled="showData"
                                size="mini"
                                icon="el-icon-minus"
                                type="danger"
                                title="删除配置"
                            ></el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-col>

            <el-col :span="12" class="col-wrap" style="height: 100%">
                <RiskBoundSetting
                    ref="bound"
                    :focusOutsideIndex="focusOutsideIndex"
                    :alwaysOpenBranch="alwaysOpenBranch"
                    :boundTypes="boundTypes"
                    :entryBranch="calcCurrentNode"
                    :factorStorage="factorStorage"
                    @set-bound-data="getBoundData"
                >
                </RiskBoundSetting>
            </el-col>
        </el-row>
        <!-- 动态参数 -->
        <ItemCalcExtendModel
            v-if="calcExtendVisible"
            :visible.sync="calcExtendVisible"
            :data="calcExtendMsg"
            :res="paramDatas"
            :branchNum="branchNum"
            @handleParam="handleCalcParam"
            :onlyLook="showData"
        ></ItemCalcExtendModel>
        <!-- 仅针对华泰HT001计算因子起作用 -->
        <HtItemCalcExtendModel
            v-if="htCalcExtendVisible"
            :visible.sync="htCalcExtendVisible"
            :data="calcExtendMsg"
            :res="paramDatas"
            :branchNum="branchNum"
            @handleParam="handleCalcParam"
            :onlyLook="showData"
        ></HtItemCalcExtendModel>
    </div>
</template>
<script lang="ts">
import { Component, Prop, Watch } from 'vue-property-decorator';
import DictionConstUtil from '@/utils/diction-const-util';
import { mixins } from 'vue-class-component';
import RiskEmitter from '@/common/mixis/risk-emitter.vue';
import XEUtils from 'xe-utils';
import RiskSettingInline from '@/common/components/risk-setting-inline.vue';
import ItemBoundExtendModel from '@/pages/baseparam/fund-group-setting/item-bound-extend-model.vue';
import ItemCalcExtendModel from '@/pages/baseparam/fund-group-setting/item-calc-extend-model.vue';
import { arrayToTree, treeToArray, recursivefilter } from '@/utils/tools';
import RiskBoundSetting from '@/common/components/risk-bound-setting.vue';
import HtItemCalcExtendModel from '@/pages/baseparam/fund-group-setting/ht-item-calc-extend-model.vue';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
    totalPage?: number;
}

@Component({
    name: 'RiskBranchSetting',
    components: {
        ItemBoundExtendModel,
        RiskSettingInline,
        ItemCalcExtendModel,
        RiskBoundSetting,
        HtItemCalcExtendModel,
    },
})
export default class RiskBranchSetting extends mixins(RiskEmitter) {
    @Prop({ required: true }) riskEntryBranchList!: any[]; // 分支列表数据
    @Prop() showData: boolean;
    @Prop() entryControls: any; // 条目基础信息
    @Prop({ default: 'look' }) status!: string; // 页面状态
    @Prop({ default: '0' }) type!: string | number; // 页面状态
    @Prop({ default: '0' }) entryType;
    @Prop() focusOutsideIndex;
    countTypeStorage: any[] = []; // 分支拼接符

    calculateShowLogic: string = ''; // 计算公式文本

    templateStorage: any[] = []; // 模板仓库
    templateStorageQuery: any[] = []; // 过滤后模板仓库

    factorStorage: any[] = []; // 计算因子仓库
    // factorStorageQuery: any[] = []; // 过滤后计算因子仓库
    branchEnum: any = {}; // 计算因子对象

    SHOW_SECURITY = process.env.ENV_CONFIG === 'project' ? window.project_config.showSecurity : process.env.SHOW_SECURITY;
    currentLevelSymbol: string = '0'; // 当前层级标识--账户层次筛选

    // entryType: any = '0'; // 风险类型
    entryBranch: any = {
        templateCode: undefined, // 选择的模板序号
        countType: '0',
        factorCode: undefined,
        branchName: '',
        branchType: '',
        entryCode: '',
    };
    riskEntryBranch: any[] = []; // 分支一维数组数据
    riskEntryBranchTree: any[] = []; // 树结构数据

    treeProps = { children: 'children', label: 'label' }; // 树字段绑定

    currentNode: any = {}; // 当前选中节点数据
    branchNo: number = 1; // 自身id
    refreshBtnLoading: boolean = false; // 刷新按钮loading状态
    boundTypes: any[] = []; // 当前因子可选范围属性
    calcCurrentNode: any = {};

    paramDatas: any = {}; // 动态参数弹窗数据
    calcExtendMsg: any[] = [];
    calcExtendVisible: boolean = false; // 因子动态参数dialog
    private htCalcExtendVisible: boolean = false; // 因子动态参数dialog - 针对华泰HT001指标
    paramCalcCode: string = '';
    branchNum: any = '';

    tempOptions: any[] = [
        { id: 1, label: '分支模板', children: [] },
        { id: 2, label: '恒生特殊计算', children: [] },
        { id: 3, label: '恒生分母', children: [] },
    ];

    factorListClass: any[] = [];

    treeselectInstance1 = null;
    treeselectInstance2 = null;

    alwaysOpenBranch: boolean = false;

    recordLastFactorCode = ''; // 记录factorCode，因为点击icon？会触发选择计算因子事件+Icon？事件
    recordLastFactorCodeWatch = false; // 记录先回显再配置操作
    selectBoolean = false;
    iconBoolean = false;
    timer = null;

    created() {
        this.$on('setentryTypes', this.entryTypeChange);
    }

    async mounted() {
        // console.error('mounted');
        // 分支拼接符
        this.countTypeStorage = DictionConstUtil.PojoToList(DictionConstUtil.RiskEntryBranchSplicingType);

        this.getFactorTree();
        // 获取所有计算因子仓库
        this.factorStorage = await DictionConstUtil.FNCalculateFactor();
        // 获取所有模板仓库
        this.templateStorage = await DictionConstUtil.FNBranchTemplate2();
        // this.treeselectInstance1 = this.$refs.treeselect1;
        // this.treeselectInstance2 = this.$refs.treeselect2;
    }

    beforeDestroy() {
        this.$off();
        // 清除定时器
        clearInterval(this.timer);
        this.timer = null;
        // this.treeselectInstance1.$destroy();
        // this.treeselectInstance2.$destroy();
        // this.$refs.treeselect1.$el.parentNode.removeChild(this.$refs.treeselect1.$el);
        // this.$refs.treeselect2.$el.parentNode.removeChild(this.$refs.treeselect2.$el);
    }

    @Watch('entryBranch.factorCode', { immediate: true, deep: true })
    watchFactorCode(newValue, oldValue) {
        if (this.iconBoolean == false && this.selectBoolean) {
            this.recordLastFactorCode = oldValue || '';
            this.iconBoolean = false;
            this.selectBoolean = false;
        } else if (oldValue == undefined) {
            this.recordLastFactorCode = newValue || '';
            this.iconBoolean = false;
            this.selectBoolean = false;
        }
    }

    /**
     * 监听父组件源数据
     */
    @Watch('riskEntryBranchList', { immediate: true, deep: true })
    watchRiskEntryBranchList(newData) {
        if (newData) {
            this.riskEntryBranch = newData.map(item => item.entryBranch);
            for (let i = 0; i < this.riskEntryBranch.length; i++) {
                const element = this.riskEntryBranch[i];
                element.entryBranchConfigs = newData[i].entryBranchConfigs;
                element.label = DictionConstUtil.RiskEntryBranchSplicingType[element.countType] + ' ' + (element.branchName || '');
                element.existDynamicCfg = element.existDynamicCfg ?? element.entryCalFacDyParam === '1';
                element.existDynamicCfgColor = element.entryCalFacDyParam === '1' ? 'green' : 'blue';
            }
        }
    }

    /**
     * 监听分支变化渲染树
     */
    @Watch('riskEntryBranch', { immediate: true, deep: true })
    watchRiskEntryBranch(newData) {
        if (newData) {
            let cloneData = XEUtils.clone(newData, true);
            this.riskEntryBranchTree = XEUtils.toArrayTree(cloneData, { key: 'branchNo', parentKey: 'parentBranchNo' });

            // 获取最大branchNo
            let branchNos = newData.map(item => item.branchNo);
            if (branchNos.length) {
                this.branchNo = Math.max(...branchNos) + 1;
            }

            // 校验及生成计算公式
            this.calculateShowLogic = this.verifyBranchConfig(this.riskEntryBranchTree);
        }
    }

    @Watch('focusOutsideIndex', { immediate: true, deep: true })
    watchFocusOutsideIndex(newVal) {
        this.alwaysOpenBranch = false;
    }

    /**
     * 分支模板树组装
     */
    get templateStorageTree() {
        // 过滤模板 （风险类型 + 复核状态）
        // this.templateStorageQuery = this.templateStorage.filter(
        //     (item: any) => item.entryType === this.entryType && !(item.modifyStatus === '1' && item.modifyType === '1')
        // );
        this.templateStorage.forEach(item => {
            if (item.entryType === this.entryType && item.templateType == '1' && !(item.modifyStatus === '1' && item.modifyType === '1')) {
                this.templateStorageQuery.push(item);
            } else if (item.templateType != '1') {
                this.templateStorageQuery.push(item);
            }
        });

        let tempOptions = JSON.parse(JSON.stringify(this.tempOptions));
        this.templateStorageQuery.forEach(item => {
            tempOptions.forEach(item2 => {
                if (Number(item.templateType) == item2.id) {
                    if (item.templateType == '1') {
                        item2.children.push({
                            label: item.templateCode + ' ' + item.templateName,
                            id: item.templateCode,
                        });
                    } else if (item.templateType == '2' || item.templateType == '3') {
                        item2.children.push({
                            label: item.specialCode + ' ' + item.specialName,
                            id: item.specialCode,
                        });
                    }
                }
            });
        });
        return tempOptions;
    }

    /**
     * 过滤计算因子 (禁用 + 风险类型)
     */
    get factorStorageQuery() {
        let res = this.factorStorage
            .filter((item: any) => item.validSymbol === '1')
            .sort((a: any, b: any) => a.entryCalculateFactorCode.replace(/[^0-9]/gi, '') - b.entryCalculateFactorCode.replace(/[^0-9]/gi, ''));

        let branchEnum = {};
        res.forEach(element => {
            branchEnum[element.entryCalculateFactorCode] = element;
        });
        if (!branchEnum['-1']) {
            branchEnum['-1'] = '';
        }
        this.branchEnum = branchEnum;
        // 账户层次筛选
        if (['0', '1'].includes(this.entryControls.originalAccountId)) {
            this.currentLevelSymbol = '0';
        } else if (['2', '3'].includes(this.entryControls.originalAccountId)) {
            this.currentLevelSymbol = '1';
        } else if (['4', '5'].includes(this.entryControls.originalAccountId)) {
            this.currentLevelSymbol = '2';
        }
        return res.filter(
            (item: any) =>
                item.entryTypes.includes(this.entryType) &&
                ((this.SHOW_SECURITY && item.levelSymbol.indexOf(this.currentLevelSymbol) !== -1) || !this.SHOW_SECURITY)
        );
    }

    /**
     * 计算因子树组装
     */
    get factorStorageTree() {
        this.factorStorageQuery.forEach(i => {
            i.id = i.entryCalculateFactorCode;
            i.label = i.entryCalculateFactorCode + ' ' + i.entryCalculateFactorName;
            i.parentId = i.classID;
            // i.isDisabled = true;
        });
        // 根据展示的计算因子向上寻找父级
        let factorKeys = this.factorStorageQuery.map(item => item.parentId);
        factorKeys = [...new Set(factorKeys)]; // 展示因子的所有上层id
        let showTree = []; // 所有需要展示的树节点 （节点下没有因子的不展示）
        factorKeys.forEach(i => {
            const arr = this.findNode(this.factorListClass, i) || [];
            showTree = [...showTree, ...arr];
        });
        showTree = this.uniqueById(JSON.parse(JSON.stringify(showTree)));
        return arrayToTree([...this.factorStorageQuery, ...showTree]);
    }

    /**
     * 监听父组件 因子分类
     */
    // @Watch('type', { deep: true })
    entryTypeChange(newData) {
        this.entryType = newData;

        if (this.currentNode.branchNo) {
            this.handleTreeClick(this.currentNode);
        }
        this.packageRiskEntryBranch([]);
        this.$notify({ title: '提示', message: '分支设置已清空，请重新设置', type: 'warning' });
    }

    /**
     * 获取因子层级关系
     */
    getFactorTree(): void {
        this.$axios({ method: 'get', url: '/original/factor/listClass' }).then((res: any) => {
            if (res) {
                this.factorListClass = res;
            }
        });
    }

    /**
     * 模板添加事件
     */
    handleAddTemplate(): void {
        if (!this.entryBranch.templateCode) {
            return;
        }

        this.$axios({ method: 'get', url: '/entry/template/branch/query/' + this.entryBranch.templateCode }).then((res: any) => {
            let templateBranch = res.riskEntryBranchs;
            if (!templateBranch || templateBranch.length === 0) {
                // 模板为空
                return;
            }

            // 获取下一分序号
            let branchNo = this.branchNo - 1;
            // 判断节点插入位置
            let parentBranchNo = 0;
            if (this.currentNode.branchNo && this.currentNode.branchType === '1') {
                // 有选中节点 且 选中节点为组分支
                parentBranchNo = this.currentNode.branchNo;
                for (let i = 0; i < templateBranch.length; i++) {
                    const element = templateBranch[i];
                    element.entryBranch.entryBranchConfigs = element.entryBranchConfigs;
                    element.entryBranch.label =
                        DictionConstUtil.RiskEntryBranchSplicingType[element.entryBranch.countType] + ' ' + (element.entryBranch.branchName || '');

                    element.entryBranch.branchNo += branchNo;
                    if (element.entryBranch.parentBranchNo === 0) {
                        element.entryBranch.parentBranchNo = this.currentNode.branchNo;
                    } else {
                        element.entryBranch.parentBranchNo += branchNo;
                    }
                    this.branchNo = element.entryBranch.branchNo;
                }
            } else {
                for (let i = 0; i < templateBranch.length; i++) {
                    const element = templateBranch[i];
                    element.entryBranch.entryBranchConfigs = element.entryBranchConfigs;
                    element.entryBranch.label =
                        DictionConstUtil.RiskEntryBranchSplicingType[element.entryBranch.countType] + ' ' + (element.entryBranch.branchName || '');

                    element.entryBranch.branchNo += branchNo;
                    if (element.entryBranch.parentBranchNo === 0) {
                    } else {
                        element.entryBranch.parentBranchNo += branchNo;
                    }
                    this.branchNo = element.entryBranch.branchNo;
                }
            }
            this.branchNo += 1;

            templateBranch = templateBranch.map(item => item.entryBranch);
            let riskEntryBranch = [...this.riskEntryBranch, ...templateBranch];

            this.packageRiskEntryBranch(riskEntryBranch);
            // 取消选中高亮 && 清空选择框
            this.restoreDefault();
        });
    }

    /**
     * 刷新事件
     */
    async handleRefresh() {
        this.refreshBtnLoading = true;
        this.getFactorTree();
        // 获取所有计算因子
        this.factorStorage = await (DictionConstUtil.SGUCalculateFactor() as any);
        this.yh_message_success('计算因子数据刷新成功');
        // 获取所有模板
        this.templateStorage = (await DictionConstUtil.FNBranchTemplateList()) as any;

        this.yh_message_success('因子模版数据刷新成功'); // 这个有问题
        this.refreshBtnLoading = false;
    }

    /**
     * 添加分支事件
     */
    handleAddTree(): void {
        // 判断节点插入位置
        let parentBranchNo = 0;
        if (this.currentNode.branchNo && this.currentNode.branchType === '1') {
            // 有选中节点 且 选中节点为组分支
            parentBranchNo = this.currentNode.branchNo;
        }
        // if (this.currentNode.branchNo && this.currentNode.branchType === '0') {
        //     // 有选中节点 且 选中节点为因子分支
        //     parentBranchNo = 0;
        // }
        // if (!this.currentNode.branchNo) {
        //     // 没有选中节点
        //     parentBranchNo = 0;
        // }
        let calc;
        // 动态参数
        let existDynamicCfg;
        let existDynamicCfgColor;
        let entryCalculateFactorDynamicParam;
        if (this.entryBranch.factorCode) {
            calc = this.branchEnum[this.entryBranch.factorCode];
            existDynamicCfg = calc.existDynamicCfg;
            existDynamicCfgColor = 'blue'; // 蓝色未填写 绿色已填写
            entryCalculateFactorDynamicParam = calc.entryCalculateFactorDynamicParam;

            if (calc.entryCalFacDyParam === '1') {
                calc.existDynamicCfg = true;
            }
        }
        let label = DictionConstUtil.RiskEntryBranchSplicingType[this.entryBranch.countType] + ' ' + (this.entryBranch.branchName || '');
        let newData = {
            branchName: this.entryBranch.branchName || '',
            branchNo: this.branchNo++,
            branchType: this.entryBranch.factorCode ? '0' : '1',
            countType: this.entryBranch.countType,
            entryCalFacDyParam: '0',
            entryCode: this.entryControls,
            factorCode: this.entryBranch.factorCode,
            parentBranchNo,
            existDynamicCfg,
            existDynamicCfgColor,
            entryCalculateFactorDynamicParam,
            label,
        };
        let riskEntryBranch = XEUtils.clone(this.riskEntryBranch, true);
        riskEntryBranch.push(newData);
        this.packageRiskEntryBranch(riskEntryBranch);

        // 取消选中高亮 && 清空选择框
        this.restoreDefault();
    }

    /**
     * 修改分支事件
     */
    handleUpdateTree(): void {
        if (!this.currentNode.branchNo) {
            this.yh_message_warn('请选择节点进行操作!');
            return;
        }
        if (this.currentNode.branchType === '1') {
            this.yh_message_warn('组分支不支持修改!');
            return;
        }

        let riskEntryBranch = this.riskEntryBranch;
        for (let i = 0; i < riskEntryBranch.length; i++) {
            const element = riskEntryBranch[i];
            if (element.branchNo === this.currentNode.branchNo) {
                element.branchName = this.entryBranch.branchName;
                element.countType = this.entryBranch.countType;
                element.factorCode = this.entryBranch.factorCode;
                element.label = DictionConstUtil.RiskEntryBranchSplicingType[this.entryBranch.countType] + ' ' + (this.entryBranch.branchName || '');
                break;
            }
        }

        this.packageRiskEntryBranch(riskEntryBranch);
        // 取消选中高亮 && 清空选择框
        this.restoreDefault();
    }

    /**
     * 删除分支事件
     */
    handleDeleteTree(): void {
        if (!this.currentNode.branchNo) {
            this.yh_message_warn('请选择节点进行操作!');
            return;
        }

        // 转为树形结构删除
        let treeData = XEUtils.clone(this.riskEntryBranchTree, true);
        treeData = recursivefilter(treeData, 'branchNo', this.currentNode.branchNo);
        let riskEntryBranch = treeToArray(treeData);

        this.packageRiskEntryBranch(riskEntryBranch);
        // 取消选中高亮 && 清空选择框
        this.restoreDefault();
    }

    /**
     * 树点击事件
     * @param node 点击的树节点数据
     */
    handleTreeClick(node: any): void {
        if (node.branchNo !== this.currentNode.branchNo) {
            this.recordLastFactorCode = node.factorCode;
            this.currentNode = JSON.parse(JSON.stringify(node));
            // 当前选中因子节点数据（范围用）
            this.calcCurrentNode = JSON.parse(JSON.stringify(node));
            this.$nextTick(() => {
                (this.$refs['tree'] as any).setCurrentKey(node.branchNo);
            });
            // 切换因子时 重置范围选中的树节点
            const boundRef: any = this.$refs['bound'];
            if (boundRef.currentNode.configId) {
                boundRef.handleTreeClick(boundRef.currentNode);
            }
        } else {
            this.recordLastFactorCode = '';
            // 取消选中高亮
            this.currentNode = {};
            // 当前选中因子节点数据（范围用）
            this.calcCurrentNode = {};
            this.$nextTick(() => {
                (this.$refs['tree'] as any).setCurrentKey();
            });
        }
        // 选择因子详情数据
        // 当前因子可选范围属性
        this.boundTypes = this.branchEnum[this.currentNode?.factorCode]?.boundTypes || [];
        // 选择框赋值
        this.entryBranch = {
            templateCode: undefined,
            countType: '0',
            factorCode: this.currentNode.factorCode,
            branchName: this.currentNode.branchName,
            branchType: '',
            entryCode: this.currentNode.entryCode,
        };
    }

    /**
     * 计算因子变动事件
     * @param val 选中因子
     */
    changBranchName(data: any): void {
        // 要实现的操作
        // this.alwaysOpenBranch = false;
        this.selectBoolean = true;
        setTimeout(() => {
            this.alwaysOpenBranch = false;
        }, 100);
        if (data) {
            this.entryBranch.branchName = data.entryCalculateFactorName;
            return;
        }
        this.entryBranch.branchName = '';
    }

    changBranchName2(data) {
        if (!data) {
            this.entryBranch.branchName = '';
        }
    }

    /**
     * 恢复默认 取消选中高亮 && 清空选择框
     */
    restoreDefault(): void {
        // 取消选中高亮
        this.currentNode = {};
        // 清空选择框
        this.entryBranch = { templateCode: undefined, countType: '0', factorCode: undefined, branchName: '', branchType: '', entryCode: '' };
    }

    /**
     * 验证配置 并生成计算方式信息
     */
    verifyBranchConfig(values: any) {
        let des = '(';
        var flag = false;
        for (let i = 0; i < values.length; i++) {
            // 4、5、6中处理
            if (values[i].countType.match('[456]')) {
                flag = true;
                des += '+';
            }
            des += { '0': '+', '1': '-', '2': '*', '3': '/', '4': 'ABS(', '5': 'MIN(', '6': 'MAX(', '7': 'DM', '8': 'TDM' }[values[i].countType];
            if (
                i === 0 &&
                (values[i].countType === '2' || values[i].countType === '3' || values[i].countType === '7' || values[i].countType === '8')
            ) {
                this.yh_message_warn('分支配置不合理，算法无法解析。请检查 ... ...');
                break;
            }
            if (values[i].children && values[i].children.length > 0) {
                des += this.verifyBranchConfig(values[i].children);
            } else {
                des += values[i].branchName;
            }

            if (flag) {
                // if (values[i].countType === '4') {
                //     des += '|';
                // } else
                if (values[i].countType === '4' || values[i].countType === '5' || values[i].countType === '6') {
                    des += ')';
                }
                flag = false;
            }
        }
        des += ')';
        return des == '()' ? '' : des;
    }

    /**
     * 计算因子动态参数设置
     */
    handleCalcExtend(data: any): void {
        let pv = (data.entryCalculateFactorDynamicParam || '').split(',');
        let paramValue = {};
        for (let value of pv) {
            if (value && value.includes(':')) {
                paramValue[value.substr(0, value.indexOf(':'))] = value.substr(value.indexOf(':') + 1);
            }
        }
        this.paramDatas = paramValue;
        this.$axios.get('/original/factor/dynamic/param/' + data.factorCode).then((res: any) => {
            if (Array.isArray(res) && res.length > 0) {
                this.calcExtendMsg = res;
                // this.calcExtendVisible = true;
                this.paramCalcCode = data.factorCode;
                this.branchNum = data.branchNo;
                if (data.factorCode == 'HT001') {
                    // 仅针对华泰HT001计算因子起作用
                    this.htCalcExtendVisible = true;
                } else {
                    this.calcExtendVisible = true;
                }
            } else {
                this.yh_message_error('动态参数配置错误!');
            }
        });
    }

    /**
     * 动态参数 回调事件
     */
    handleCalcParam(data, branchNum): void {
        let riskEntryBranch = XEUtils.clone(this.riskEntryBranch, true);
        for (let i = 0; i < riskEntryBranch.length; i++) {
            const element = riskEntryBranch[i];
            if (element.factorCode === this.paramCalcCode && element.branchNo === branchNum) {
                element.entryCalculateFactorDynamicParam = data;
                element.entryCalFacDyParam = '1';
                element.existDynamicCfgColor = 'green';
                break;
            }
        }
        this.calcExtendVisible = false;
        this.htCalcExtendVisible = false;
        this.packageRiskEntryBranch(riskEntryBranch);
    }

    /**
     * 组装回数据 将数据传回父组件
     */
    packageRiskEntryBranch(riskEntryBranch: any[]): void {
        let riskEntryBranchList = [];
        for (let i = 0; i < riskEntryBranch.length; i++) {
            const element = riskEntryBranch[i];
            riskEntryBranchList.push({ entryBranch: element, entryBranchConfigs: element.entryBranchConfigs || [] });
        }

        this.$emit('set-branch-data', riskEntryBranchList);
    }

    getBoundData(data: any) {
        let riskEntryBranch = this.riskEntryBranch;
        for (let index = 0; index < riskEntryBranch.length; index++) {
            const element = riskEntryBranch[index];
            if (element.branchNo === data.branchNo && element.factorCode === data.factorCode) {
                element.entryBranchConfigs = data.entryBranchConfigs;
                this.calcCurrentNode = {};
                this.currentNode = {};
                this.handleTreeClick(element);
            }
        }
        this.packageRiskEntryBranch(riskEntryBranch);
    }

    /**
     * 对象数组 根据对象内的某个属性去重
     */
    uniqueById(arr) {
        const map = {};
        const result = [];
        for (let i = 0; i < arr.length; i++) {
            const item = arr[i];
            if (!map[item.id]) {
                map[item.id] = true;
                // item.id = item.id;
                // item.label = item.title;
                delete item.children;
                result.push(item);
            }
        }
        return result;
    }

    /**
     * 在树结构中查找某个节点， 并返回与之关联的节点
     */
    findNode(tree, targetId, result = []) {
        for (let i = 0; i < tree.length; i++) {
            const { id, children } = tree[i];
            if (id === targetId) {
                return result.concat(tree[i]);
            } else if (children) {
                const res = this.findNode(children, targetId, result.concat(tree[i]));
                if (res) {
                    return res;
                }
            }
        }
        return null;
    }
}
</script>
<style lang="scss" scoped>
@import '@/assets/style/item-setting.scss';
/deep/ .vue-treeselect {
    height: 26px !important;
    .vue-treeselect__control {
        height: 28px !important;
    }
    .vue-treeselect__multi-value-item-container,
    .vue-treeselect__limit-tip {
        padding-top: 0 !important;
        padding-right: 0 !important;
    }

    .vue-treeselect__input-container {
        padding-top: 0 !important;
        .vue-treeselect__input {
            height: 24px;
            line-height: 24px;
        }
    }

    .vue-treeselect__placeholder,
    .vue-treeselect__single-value {
        height: 28px;
        line-height: 28px;
    }
}

/deep/ .vue-treeselect__multi-value-item,
/deep/ .vue-treeselect__limit-tip-text {
    background-color: #f4f4f5 !important;
    border-color: #e9e9eb !important;
    color: #909399 !important;
    height: 15px;
}

/deep/ .vue-treeselect__value-remove {
    color: #909399 !important;
}

/deep/ .vue-treeselect__multi-value {
    height: 20px;
    margin-bottom: 3px;
}

/deep/ .el-select .el-input__icon {
    line-height: 28px;
}
</style>
<style lang="scss">
.vue-treeselect--open-below .vue-treeselect__menu {
    top: 1px !important;
}
.vue-treeselect--open-above .vue-treeselect__menu {
    top: 27px !important;
    height: 24vh !important;
}
/deep/ .vue-treeselect__menu-container .vue-treeselect__menu {
    border: 1px solid red !important;
    position: relative;
    z-index: 99999999 !important;
}
.factor-dialog .el-dialog {
    position: absolute;
    right: 20px;
}
</style>
